<?php

namespace Biz\service\advertisement;

class STimeRecorder
{

    private $title_stack = [];
    private $time_stack = [];

    public static function getInstance(): STimeRecorder
    {
        $instance = new self;
        $instance->record('start');
        return $instance;
    }

    public function record($title)
    {
        $this->title_stack[] = $title;
        $this->time_stack[] = $this->t();
    }

    public function t()
    {
        return microtime(true);
    }

    public function __toString()
    {
        $msg = [];
        foreach ($this->title_stack as $k => $title) {
            $time = $this->time_stack[$k];
            $before = $this->time_stack[$k - 1] ?? 0;
            $msg[] = implode("\t", [
                $title,
                \DateTime::createFromFormat('U.u', $time)->format('Y-m-d H:i:s.u'),
                $before ? number_format($time - $before, 3) : '-'
            ]);
        }
        return implode(PHP_EOL, $msg);
    }
}